#include <stdio.h>
#include <assert.h>
#include <ctype.h>
#include <stdlib.h>


// Reads from stdin into a dynamically allocated buffer until a newline
// character is entered. Eliminates preceding whitespace.
static char * getLine(char * prompt) {

  int start_size = 16;
  char * buf = Malloc( start_size * sizeof(char) );
  printf("%s ", prompt);

  while ( 1 ) {
    int c = getchar();
    if ( c == EOF ) {
      return NULL;
    }
    if ( ! isspace(c) ) {
      ungetc( c, stdin );
      break;
    }
  }

  int idx = 0;
  while ( 1 ) {
    int c = getchar();
    if ( c == EOF || c == '\n' ) {
      buf[idx] = '\0';
      break;
    }
    buf[idx] = c;
    if ( idx == start_size - 1 ) { // Buffer full
      start_size *= 2;
      buf = realloc( buf, start_size );
      assert( buf );
    }
    idx ++;
  }

  return buf;
}

int readInt( char * prompt ) {
  int toRet;
  int numRead;
  do {
    char * input = getLine( prompt );
    numRead = sscanf( input, "%d", &toRet );
    free ( input );
  } while ( numRead != 1 );
  return toRet;
}

float readFloat( char * prompt ) {
  float toRet;
  int numRead;
  do {
    char * input = getLine( prompt );
    numRead = sscanf( input, "%f", &toRet );
    free ( input );
  } while ( numRead != 1 );
  return toRet;
}

double readDouble( char * prompt ) {
  double toRet;
  int numRead;
  do {
    char * input = getLine( prompt );
    numRead = sscanf( input, "%lf", &toRet );
    free ( input );
  } while ( numRead != 1 );
  return toRet;
}

char * readString( char * prompt ) {

  return getLine( prompt );

}


